package com.jt;

import org.apache.http.HttpHeaders;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/*构建一个全局的请求url黑名单过滤器，
* 对请求url进行校验，合法则放行，不合法则给出反馈*/
@Component
//@ConfigurationProperties("web.requst")
public class BlackUrlGlobalFilter implements GlobalFilter, Ordered {

    //定义一个黑名单集合（在此集合中的url不允许访问我们的资源）
    private List<String> blackUrls = new ArrayList<>();
    public BlackUrlGlobalFilter(){
        blackUrls.add("/nacos/provider/echo/9002");
        blackUrls.add("/nacos/provider/echo/9003");
    }
    @Override
    public Mono<Void> filter(ServerWebExchange exchange,
                             GatewayFilterChain chain) {
        //1，获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2,获取请求的路径（不需要ip和端口），例如/nacos/privider/echo/9001
        String requestPath = request.getURI().getPath();
        //3，判断请求路径是否是黑名单url，假如是则给出反馈
        if (blackUrls.contains(requestPath)){
            //结果处理方案1：抛出异常
            //throw new RuntimeException("这个请求已经列入黑名单");
            //结果处理方案2，响应一个error消息
            response.getHeaders()
                    .add(HttpHeaders.CONTENT_TYPE,"text/html;charset=utf-8");
            DataBuffer data = response.bufferFactory().
                    wrap("当前url不允许访问资源".getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(data));

        }
        return chain.filter(exchange);
    }


    /*定义过滤器的优先级，数字越小，优先级越高*/
    @Override
    public int getOrder() {
        return 0;
    }
}
